import { forwardRef, isValidElement, useImperativeHandle, useRef, useState } from 'react';

import { Modal } from 'antd';

const getLeafChildren = (children: unknown) => {
  if (Array.isArray(children)) {
    for (let i = 0; i < children.length; i++) {
      const child = children[i];
      if (isValidElement(child)) {
        if ((child.props as { children: unknown }).children) {
          return getLeafChildren((child.props as { children: unknown }).children);
        }
      }
    }
  }

  if (isValidElement(children)) {
    if ((children.props as { children: unknown }).children) {
      return getLeafChildren((children.props as { children: unknown }).children);
    }
  }

  return children;
};

export type CaptchaProps = {
  config?: Partial<TACConfig>;
};

export type CaptchaRef = {
  open: (config?: CaptchaProps['config']) => void;
};

let index = 0;

const Captcha = forwardRef<CaptchaRef, CaptchaProps>(({ config }, ref) => {
  const id = useRef(`captcha-${index++}`);
  const tacInstance = useRef<TACInstance>();
  const [open, setOpen] = useState(false);
  const [argConfig, setArgConfig] = useState<CaptchaProps['config']>();

  useImperativeHandle(ref, () => {
    return {
      open: (_config) => {
        setOpen(true);
        setArgConfig(_config);
      }
    };
  });

  const afterOpenChange = (open: boolean) => {
    if (!open) {
      tacInstance.current?.destroyWindow();
    } else {
      const combinedConfig = {
        ...config,
        ...argConfig
      };

      window
        .initTAC(
          './lib/captcha/tac',
          {
            // 生成接口 (必选项,必须配置, 要符合tianai-captcha默认验证码生成接口规范)
            requestCaptchaDataUrl: '/api/app/captcha/get?type=CONCAT',
            // 验证接口 (必选项,必须配置, 要符合tianai-captcha默认验证码校验接口规范)
            validCaptchaUrl: '/api/app/captcha/check',
            // 验证码绑定的div块 (必选项,必须配置)
            bindEl: `#${id.current}`,
            // bindEl: "#captcha-box",
            captchaType: 'CONCAT',
            ...combinedConfig,
            // 验证成功回调函数(必选项,必须配置)
            validSuccess: (res, c, tac) => {
              setOpen(false);
              config?.validSuccess?.(res, c, tac);
              argConfig?.validSuccess?.(res, c, tac);
            },
            // 验证失败的回调函数(可忽略，如果不自定义 validFail 方法时，会使用默认的)
            validFail: (res, c, tac) => {
              config?.validFail?.(res, c, tac);
              argConfig?.validFail?.(res, c, tac);
              // 验证失败后重新拉取验证码
              tac.reloadCaptcha();
            },
            // 刷新按钮回调事件
            btnRefreshFun: (el, tac) => {
              config?.btnRefreshFun?.(el, tac);
              argConfig?.btnRefreshFun?.(el, tac);
              tac.reloadCaptcha();
            },
            // 关闭按钮回调事件
            btnCloseFun: (el, tac) => {
              config?.btnCloseFun?.(el, tac);
              argConfig?.btnCloseFun?.(el, tac);
              setOpen(false);
            }
          },
          {
            logoUrl: null
          }
        )
        .then((tac) => {
          tac.init();
          tacInstance.current = tac;
        })
        .catch((e) => {
          console.log('初始化tac失败', e);
        });
    }
    setOpen(open);
  };

  return (
    <Modal
      open={open}
      afterOpenChange={afterOpenChange}
      footer={null}
      closable={false}
      width={'fit-content'}
      modalRender={(modal) => {
        return getLeafChildren(modal) as React.ReactNode;
      }}
      centered
    >
      <div
        id={id.current}
        style={{
          pointerEvents: 'all'
        }}
      />
    </Modal>
  );
});

Captcha.displayName = 'Captcha';

export default Captcha;
